<?php
/*                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                            O\ = /O
 *                        ____/`---'\____
 *                      .   ' \\| |// `.
 *                       / \\||| : |||// \
 *                     / _||||| -:- |||||- \
 *                       | | \\\ - /// | |
 *                     | \_| ''\---/'' | |
 *                      \ .-\__ `-` ___/-. /
 *                   ___`. .' /--.--\ `. . __
 *                ."" '< `.___\_<|>_/___.' >'"".
 *               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *                 \ \ `-. \_ __\ /__ _/ .-` / /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *
 *         .............................................
 *                  佛祖保佑             永无BUG
 *
 * ======================================================
 * @author: Ethan Lu <ethan.lu@qq.com>
 * 
 */

namespace common\behaviors;

use common\models\VenueAttribute;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

class VenueAttributeBehavior extends Behavior
{

    /** @var  ActiveRecord */
    public $owner;

    public $attribute = 'venueAttributes';

    /**
     * 属性关联表
     */
    public $attributeRelation;

    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
            ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete'
        ];
    }

    public function afterFind()
    {
        $models = $this->owner->{$this->attributeRelation};
        $this->owner->{$this->attribute} = $this->enrichData($models);
    }

    public function afterInsert()
    {
        if($this->owner->{$this->attribute}) {
            $this->saveDataRelation($this->getPostAttributes($this->owner->{$this->attribute}));
        }
    }

    public function afterUpdate()
    {
        // 获取数据库中已存在的数据
        $models = $this->owner->{$this->attributeRelation};
        // 提交的数据
        $attributes = $this->getPostAttributes($this->owner->{$this->attribute});
        // 新属性
        $newAttribute = [];
        foreach($models as $model) {
            $attr = $model->toArray(['attribute_id', 'value']);
            if(!in_array($attr, $attributes)) {
                $model->delete();
            }
        }

        $modelsArray = $this->getPostAttributes($models);
        foreach($attributes as $attr) {
            if(!in_array($attr, $modelsArray)) {
                if(!empty($attr['value'])) {
                    $newAttribute[] = $attr;
                }
            }
        }
        $this->saveDataRelation($newAttribute);
    }

    protected function getPostAttributes($postData)
    {
        $attributes = [];
        foreach($postData as $k => $v) {
            if(is_object($v)) {
                $attributes[] = $v->toArray(['attribute_id', 'value']);
            } else {
                if(empty($v['value'])) continue;
                if(is_array($v['value'])) {
                    foreach($v['value'] as $attr) {
                        array_push($attributes, ['attribute_id' => $v['attribute_id'], 'value' => $attr]);
                    }
                } else {
                    array_push($attributes, ['attribute_id' => $v['attribute_id'], 'value' => $v]);
                }
            }

        }
        return $attributes;
    }

    public function afterDelete()
    {
        /** @var VenueAttribute $model */
        $modelClass = $this->getAttributeRelation()->modelClass;
        $model = new $modelClass;
        $model->deleteAll('venue_id = :venue_id', [':venue_id' => $this->owner->id]);
    }

    /**
     * @return \yii\db\ActiveQuery|\yii\db\ActiveQueryInterface
     */
    protected function getAttributeRelation()
    {
        return $this->owner->getRelation($this->attributeRelation);
    }

    /**
     * 保存关联属性
     * @param $datas
     */
    protected function saveDataRelation($datas)
    {

        $modelClass = $this->getAttributeRelation()->modelClass;
        foreach ($datas as $data) {
            $model = new $modelClass;
            $model->load($data, '');
            $this->owner->link($this->attributeRelation, $model);
        }
    }

    protected function enrichData($datas)
    {
        $attributes = [];

        // 获取属性id
        $attribute_ids = array_unique(ArrayHelper::getColumn($datas, 'attribute_id'));


        foreach($attribute_ids as $index => $id) {
            $attributes[$id] = $datas[$index];
            $value = [];
            foreach($datas as $k => $v) {
                if($id == $v->attribute_id) {
                    array_push($value, $v->value);
                }
            }
            $attributes[$id]->value = $value;
        }
        return $attributes;
    }
}